<template>
  <div>
    <div class="login-page">
      <div class="form">
        <!-- 找回密码表单 -->
        <div class="found-form" v-if="isLoginPage == 'found'">
          <router-link tag="button" to="/index" class="mdui-btn mdui-btn-icon"
            ><i class="mdui-icon material-icons">exit_to_app</i></router-link
          >
          <!-- 找回->用户名 -->
          <div
            class="mdui-textfield mdui-textfield-floating-label"
            v-show="!foundForm.enterPassword"
          >
            <label class="mdui-textfield-label">Username</label>
            <input
              class="mdui-textfield-input"
              type="text"
              v-model="foundForm.username"
              @keyup.enter="sendResetCode()"
            />
          </div>
          <div
            class="found"
            v-show="!foundForm.enterPassword"
          >
            <!-- 验证码输入框 -->
            <div class="mdui-textfield mdui-textfield-floating-label">
              <label class="mdui-textfield-label">Code</label>
              <input
                class="found-mail mdui-textfield-input"
                type="number"
                v-model.number="foundForm.resetCode"
                @keyup.enter="foundUser()"
              />
            </div>
            <!-- 发送验证码按钮 -->
            <button
              class="disabled found-btn mdui-btn mdui-btn-raised mdui-btn-dense mdui-color-theme-accent mdui-ripple"
              v-bind="{ disabled: isSending }"
              @click="sendResetCode()"
            >
              <i class="mdui-icon material-icons">cached</i>
              <span>{{foundForm.reSendBtn}}</span>
            </button>
          </div>
          <!-- 新密码输入框 -->
          <newpasswd-input
            v-show="foundForm.enterPassword"
            @newPassword='getNewpassword'
            @enterPasswd='enterPasswd'
          ></newpasswd-input>
          <button
            class="mdui-btn mdui-btn-block mdui-color-blue-600 mdui-ripple"
            @click="foundForm.enterPassword ? resetPassword() :foundUser()"
          >
            提交
          </button>
          <p class="message">
            记起密码了?
            <span class="span-reg-login" @click="isLoginPage = 'login'"
              >马上登录</span
            >
          </p>
        </div>
        <!-- 注册表单 -->
        <div class="register-form" v-else-if="isLoginPage == 'reg'">
          <router-link
            tag="button"
            to="/index"
            class="exit mdui-btn mdui-btn-icon"
            ><i class="mdui-icon material-icons">exit_to_app</i></router-link
          >
          <!-- 注册邮箱 -->
          <div class="mdui-textfield mdui-textfield-floating-label">
            <i class="mdui-icon material-icons">email</i>
            <label class="mdui-textfield-label">Email</label>
            <input
              class="mdui-textfield-input"
              type="email"
              v-model="regForm.email"
            />
          </div>
          <!-- 注册用户名 -->
          <div class="mdui-textfield mdui-textfield-floating-label">
            <i class="mdui-icon material-icons">account_circle</i>
            <label class="mdui-textfield-label">User name</label>
            <input
              v-model="regForm.username"
              class="mdui-textfield-input"
              type="text" />
          </div>
          <div class="mdui-textfield mdui-textfield-floating-label">
            <i class="mdui-icon material-icons">lock</i>
            <label class="mdui-textfield-label">Password</label>
            <input
              v-model="regForm.password"
              class="mdui-textfield-input"
              type="password" />
          </div>
          <!-- addr message -->
          <div class="mdui-textfield mdui-textfield-floating-label">
            <i class="mdui-icon material-icons">textsms</i>
            <label class="mdui-textfield-label">Message</label>
            <textarea
              v-model="regForm.addrMsg"
              class="mdui-textfield-input"
            ></textarea>
          </div>
          <button
            class="mdui-btn mdui-btn-block mdui-color-blue-600 mdui-ripple"
            @click="regUser()"
          >
            注册
          </button>
          <p class="message">
            已经有账号了?
            <span class="span-reg-login" @click="isLoginPage = 'login'"
              >马上登录</span
            >
          </p>
        </div>
        <!-- 登录表单 -->
        <div
          class="login-form"
          v-else
        >
          <router-link tag="button" to="/index" class="mdui-btn mdui-btn-icon"
            ><i class="mdui-icon material-icons">exit_to_app</i></router-link
          >
          <div class="mdui-textfield mdui-textfield-floating-label">
            <label class="mdui-textfield-label">Username</label>
            <input
              class="mdui-textfield-input"
              type="text"
              v-model="username"
              ref="loginFormInput"
            />
          </div>
          <div class="mdui-textfield mdui-textfield-floating-label">
            <label class="mdui-textfield-label">Password</label>
            <input
              v-model="password"
              @keyup.enter="loginForm.canEnter ? login() : null"
              class="mdui-textfield-input"
              type="password"
            />
          </div>
          <button
            @click="login()"
            :disabled="!loginForm.loginBtn"
            class="mdui-btn mdui-btn-block mdui-color-blue-600 mdui-ripple"
          >
            登录
          </button>
          <p class="message">
            还没有注册?
            <span class="span-reg-login" @click="isLoginPage = 'reg'"
              >创建一个账号</span
            >
          </p>
          <p class="message">
            密码忘记了?
            <span class="span-reg-login" @click="isLoginPage = 'found'"
              >找回密码</span
            >
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import mdui from 'mdui'
import apiConfig from '@/api/apiConfig'
import newPasswordInput from '@/components/NewPasswordInput'
// import axios from 'axios'
export default {
  data () {
    return {
      username: '',
      password: '',
      isLoginPage: 'login',
      found_code: '',
      isSending: false,
      loginForm: {
        canEnter: true,
        loginBtn: true
      },
      regForm: {
        email: '',
        username: '',
        password: '',
        addrMsg: ''
      },
      foundForm: {
        username: '',
        resetCode: '',
        reSendBtn: '发送',
        codeToken: '',
        passwdInput: true,
        enterPassword: false,
        newPasswd: ''
      }
    }
  },
  methods: {
    login: async function () {
      try {
        this.loginForm.loginBtn = false
        this.loginForm.canEnter = false
        if (this.username.length < 4 || this.username === '' || this.password === '') {
          mdui.snackbar({
            message: '输入的数据不符合要求，请重新检查',
            position: 'top'
          })
          return
        }
        const conf = apiConfig.user.login(this.username, this.password)
        const datas = await this.$axios(conf)
        if (datas.status === 200) {
          this.$store.commit('setToken', datas.data.data.token)
          this.$store.commit('setUser', datas.data.data.username)
          localStorage.setItem('token', datas.data.data.token)
          localStorage.setItem('username', datas.data.data.username)
          mdui.snackbar({
            message: '登录成功',
            position: 'top',
            timeout: 2000,
            onClose: () => {
              this.$router.push('/cloud')
            }
          })
        } else {
          mdui.snackbar({ message: datas.message, position: 'top' })
        }
      } catch (error) {
        mdui.snackbar({ message: error.message, position: 'top' })
      } finally {
        this.loginForm.loginBtn = true
        this.loginForm.canEnter = true
      }
    },
    async regUser () {
      const conf = apiConfig.user.regUser(this.regForm.email, this.regForm.username, this.regForm.password, this.regForm.addrMsg)
      try {
        await this.$axios(conf)
        this.username = this.regForm.username
        mdui.snackbar('注册成功，正在跳转...', {
          position: 'top',
          timeout: 2000,
          onClosed: () => {
            this.isLoginPage = 'login'
            setTimeout(() => {
              this.$refs.loginFormInput.focus()
            }, 500)
          }
        })
      } catch (error) {
        mdui.snackbar(error.message, {
          position: 'top',
          timeout: 2000
        })
        console.log('regUser catch->', error)
      }
    },
    async foundUser () {
      console.log('123')
      const conf = apiConfig.user.checkCode(this.foundForm.username, this.foundForm.resetCode, this.foundForm.codeToken)
      try {
        const data = await this.$axios(conf)
        // console.log(data)
        if (data.status === 200) {
          this.$store.commit('setToken', data.data.data.resetToken)
          this.foundForm.enterPassword = true
        }
      } catch (error) {
        console.log(error)
      }
    },
    async sendResetCode () {
      console.log('sendCode')
      if (this.foundForm.username.length < 5) {
        mdui.snackbar('用户名未填写', {
          position: 'top',
          timeout: 2000
        })
        return null
      }
      this.isSending = true
      let sec = 60
      const conf = apiConfig.user.sendCode(this.foundForm.username)
      this.$axios(conf).then(res => {
        this.foundForm.codeToken = res.data.data.token
        mdui.snackbar(res.data.message, {
          position: 'top',
          timeout: 2000
        })
      }).catch(e => {
        console.log(e)
      })
      const timeInterval = setInterval(() => {
        this.foundForm.reSendBtn = `${sec--}秒`
      }, 1000)
      setTimeout(() => {
        this.isSending = false
        this.foundForm.reSendBtn = '发送'
        clearInterval(timeInterval)
      }, sec * 1000)
    },
    async resetPassword () {
      console.log('resetPassword')
      try {
        const conf = apiConfig.user.renewPasswd(this.foundForm.newPasswd)
        const data = await this.$axios(conf)
        if (data.status === 200) {
          mdui.snackbar({
            message: data.data.message,
            position: 'top',
            timeout: 2000,
            onClose: () => {
              this.isLoginPage = 'login'
            }
          })
        } else {
          mdui.snackbar({ message: data.message, position: 'top' })
        }
      } catch (error) {
        console.log(error)
      }
    },
    getNewpassword (newPassword) {
      console.log('get')
      this.foundForm.newPasswd = newPassword
    },
    enterPasswd (newPasswd) {
      console.log('enter')
      this.foundForm.newPasswd = newPasswd
      this.resetPassword()
    }
  },
  components: {
    'newpasswd-input': newPasswordInput
  }
}
</script>

<style scoped>
@import url(https://fonts.googleapis.com/css?family=Roboto:300);
.found {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  justify-content: space-around;
  animation: 0.2s changePage ease-in;
}
.found button {
  margin: 10px;
}
.span-reg-login {
  cursor: pointer;
  color: #42a5f5;
}
.span-reg-login:hover,
.span-reg-login:active,
.span-reg-login:focus {
  border-bottom: 1px solid #42a5f5;
}
.login-page {
  width: 360px;
  padding: 8% 0 0;
  margin: auto;
}
.form {
  position: relative;
  z-index: 1;
  background: #ffffff;
  max-width: 360px;
  margin: 0 auto 100px;
  padding: 45px;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
  display: flex;
  flex-direction: column;
}

.form .register-form {
  /* display: none; */
  animation: 0.2s changePage ease-in;
}
.form .login-form {
  animation: 0.2s changePage ease-in;
}
.form p {
  text-align: center;
}
@keyframes changePage {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>
